package org.idea.spring.dependency.inject.setter;

import org.idea.spring.ioc.bean.Person;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;

/**
 * 通过api的方式进行注入实现
 *
 * @Author linhao
 * @Date created in 11:11 下午 2021/4/21
 */
public class ApiDependencyInjectDemo {

    @Bean
    public Person myPerson(){
        return new Person(1,"idea");
    }

    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        applicationContext.register(ApiDependencyInjectDemo.class);
        BeanDefinition personBeanDefinition = createUserBeanDefinition();
        applicationContext.registerBeanDefinition("personHolder",personBeanDefinition);
        applicationContext.refresh();
        PersonHolder personHolder = applicationContext.getBean(PersonHolder.class);
        System.out.println(personHolder.getPerson());
        applicationContext.close();
    }

    private static BeanDefinition createUserBeanDefinition() {
        BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(PersonHolder.class);
        //注意这里的add方法有多种类型，需要注意下细节点
        beanDefinitionBuilder.addPropertyReference("person","myPerson");
        return beanDefinitionBuilder.getBeanDefinition();
    }
}
